package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.mapper.RoleMapper;
import com.iretailer.report.model.Menus;
import com.iretailer.report.model.Role;
import com.iretailer.report.model.RoleCompany;
import com.iretailer.report.model.RoleMenu;
import com.iretailer.report.util.GetId;
import com.iretailer.report.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xjw
 * @Date: 2019/1/24 11:43
 * @Description:
 */
@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuService roleMenuService;

    public PageResult<RoleCompany> selectRolePage(String parentId, String roleName, QueryOption queryOption) {
        Page page = new Page<RoleCompany>(1, Long.MAX_VALUE);
        QueryWrapper<RoleCompany> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("1", 1);
        if (!parentId.equals("-")) {
            List<String> childs = getTreeId(parentId);
            childs.add(parentId);
            queryWrapper.in("parentId", childs);
//            queryWrapper.eq("parentId", parentId);
        }
        if (roleName != null) {
            queryWrapper.like("name", roleName);
        }
        queryOption.judge(page, queryWrapper);
        roleMapper.selectPageRoleCompany(page, queryWrapper);
//        IPage pageInfo = roleMapper.selectPage(page, queryWrapper);
//        return new PageResult<>(pageInfo.getTotal(), pageInfo.getRecords());
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    /**
     * 根据 parentId 查出所有的 子id
     */
    public List<String> getTreeId(String parentId) {
        List<Role> allRole = list(new QueryWrapper<Role>().lambda().orderByAsc(Role::getId));
        List<Role> roles = convertTree(allRole, parentId);
        List<String> result = convertTreeIds(roles, new HashSet<>());
        return result;
    }

    public List<Role> convertTree(List<Role> roles, String parentId) {
        List<Role> result = new ArrayList<>();
        roles.forEach(it -> {
            if (it.getParentId() != null && (it.getParentId()).equals(parentId)) {
                List<Role> children = convertTree(roles, it.getId());
                it.setChildren(children);
                result.add(it);
            }
        });
        return result;
    }

    public List<String> convertTreeIds(List<Role> roles, Set<String> result) {
        roles.forEach(it -> {
            result.add(it.getId());
            if (it.getChildren() != null) {
                convertTreeIds(it.getChildren(), result);
            }
        });
        return new ArrayList<>(result);
    }


    /**
     * 根据 parentId 查出 s_roles 表中所有的 role
     */
    public List<Role> selectRolesByParentId(String parentId) {
        return roleMapper.selectRolesByParentId(parentId);
    }


    /**
     * 添加 或者 更新
     */
      @Transactional(propagation = Propagation.REQUIRED)
    public boolean saveOrUpdate(Role role, String parentId, List<RoleMenu> roleMenus, String userName) {
        role.setUpdateTime(LocalDateTime.now());
        role.setUpdateUser(userName);
        if (StringUtil.notEmpty(role.getId())) {
            roleMapper.updateById(role);
        } else {
            role.setParentId(parentId);
            role.setId(GetId.UUID());
            roleMapper.insert(role);
        }
        if (roleMenus != null) {
            //根据 roleId 删除所有的 s_roles_menus
//            roleMapper.deleteRolesMenusByRoleId(role.getId());
            roleMenuService.remove(new QueryWrapper<RoleMenu>().lambda().eq(RoleMenu::getRoleId, role.getId()));
            for (RoleMenu roleMenu : roleMenus) {
                roleMenu.setRoleId(role.getId());
            }
            roleMenuService.saveBatch(roleMenus);
//            roleMenuService.insertBatchRolesMenus(role.getId(), role.getMenuIds());
        }
        return true;
    }

      @Transactional(propagation = Propagation.REQUIRED)
    public boolean deleteByIds(List<String> ids) {
        roleMenuService.remove(new QueryWrapper<RoleMenu>().lambda().in(RoleMenu::getRoleId, ids));
        removeByIds(ids);
        return true;
    }

    /**
     * 根据 menusId 查询  主要用于删除 Menus时查询是否有关联
     */
    public List<Role> selectByMenusId(String menusId) {
        return roleMapper.selectByMenusId(menusId);
    }


    /**
     * 根据 parentId 的集合查询
     * deleteFlag 查询 null 查询全部， 1 为正在使用，-1 为删除
     */
    public List<Role> selectRolesByParentIds(List<String> parentIds, Integer deleteFlag) {
        return roleMapper.selectRolesByParentIds(parentIds, deleteFlag);
    }
}
